<?php

namespace falcon5\inc\WPProviders;

use falcon5\inc\Base\Common;
use falcon5\inc\Base\ServiceProviderInterface;

/**
 * Class RegisterAdminNotices
 * @package falcon5\inc\WPProviders
 * @desc Admin notification messages
 */
class AdminNotices implements ServiceProviderInterface
{
    private static $deactivatePlugins = [
        'WP Translator' => 'wptranslator/WPTranslator.php',
        'TranslatePress' => 'translatepress-multilingual/index.php',
        'Google Language Translator' => 'google-language-translator/google-language-translator.php',
        'Google Website Translator' => 'google-website-translator/google-website-translator.php',
        'Weglot' => 'weglot/weglot.php',
        'TransPosh' => 'transposh-translation-filter-for-wordpress/transposh.php',
        'Advanced Google Translate' => 'advanced-google-translate/advanced-google-translate.php',
        'My WP Translate' => 'my-wp-translate/my-wp-translate.php',
        'WPML Multilingual CMS' => 'sitepress-multilingual-cms/sitepress.php',
        'Gtranslate' => 'gtranslate/gtranslate.php',
        'Polylang' => 'polylang/polylang.php',
    ];

    private $notices = [];

    public function register()
    {
        add_action('admin_notices', [$this, 'admin_notice']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('wp_ajax_falcon5_deactivate_plugin', [$this, 'ajax_deactivate_plugin']);
    }

    /**
     * Enqueue necessary scripts for AJAX functionality
     */
    public function enqueue_scripts()
    {
        wp_enqueue_script('jquery');
        
        // Add inline script for handling AJAX deactivation
        wp_add_inline_script('jquery', '
            jQuery(document).ready(function($) {
                $(".falcon5-deactivate-plugin").on("click", function(e) {
                    e.preventDefault();
                    
                    var pluginElement = $(this);
                    var pluginData = {
                        action: "falcon5_deactivate_plugin",
                        plugin: pluginElement.data("plugin"),
                        nonce: pluginElement.data("nonce")
                    };
                    
                    pluginElement.html("<span class=\"spinner is-active\" style=\"float:none;margin:0;display:inline-block;\"></span> Deactivating...");
                    
                    $.post(ajaxurl, pluginData, function(response) {
                        if (response.success) {
                            pluginElement.closest("li").fadeOut(300, function() { 
                                $(this).remove(); 
                                // If no more conflicting plugins, remove the entire notice
                                if($(".fc5-notice-body li").length === 0) {
                                    $(".fc5-admin-notice").remove();
                                }
                            });
                        } else {
                            pluginElement.html("Error: " + response.data.message);
                        }
                    }).fail(function() {
                        pluginElement.html("Request failed. Please try again.");
                    });
                });
            });
        ');
    }

    /**
     * AJAX handler for deactivating plugins
     */
    public function ajax_deactivate_plugin()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'falcon5_deactivate_plugin')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check if plugin parameter is provided
        if (!isset($_POST['plugin']) || empty($_POST['plugin'])) {
            wp_send_json_error(['message' => 'No plugin specified']);
            return;
        }

        $plugin = sanitize_text_field($_POST['plugin']);

        // Check if the plugin exists in our list of conflicting plugins
        $plugin_exists = false;
        foreach (self::$deactivatePlugins as $name => $pluginFile) {
            if ($pluginFile === $plugin) {
                $plugin_exists = true;
                break;
            }
        }

        if (!$plugin_exists) {
            wp_send_json_error(['message' => 'Plugin not found in the list of conflicting plugins']);
            return;
        }

        // Check if the plugin is active
        if (!is_plugin_active($plugin)) {
            wp_send_json_error(['message' => 'Plugin is not active']);
            return;
        }

        // Deactivate the plugin
        include_once(ABSPATH . 'wp-admin/includes/plugin.php');
        
        // Call deactivate_plugins and check if the plugin is still active afterward
        deactivate_plugins($plugin);
        
        // Check if the plugin was successfully deactivated
        if (!is_plugin_active($plugin)) {
            wp_send_json_success(['message' => 'Plugin deactivated successfully']);
        } else {
            wp_send_json_error(['message' => 'Failed to deactivate plugin']);
        }
    }

    function admin_notice() {
        $this->checkDeactivatePlugins()->registerAdminNotices();
    }

    public function checkDeactivatePlugins()
    {
        foreach (self::$deactivatePlugins as $name => $pluginFile) {
            if(is_plugin_active($pluginFile)) {
                $nonce = wp_create_nonce('falcon5_deactivate_plugin');
                $this->notices['deactivate_plugin_'.strtolower(str_replace(' ', '', $name))] = array(
                    'title' => sprintf(__('Please deactivate %s plugin', 'falcon5'), $name),
                    'msg' => sprintf(__('%s plugin causes conflicts with '. Common::PLUGIN_NAME .'.', 'falcon5'), $name),
                    'link' => '<span class="dashicons dashicons-dismiss"></span><a href="#" class="falcon5-deactivate-plugin" data-plugin="'.esc_attr($pluginFile).'" data-nonce="'.esc_attr($nonce).'">' . sprintf(__('Deactivate %s plugin', 'falcon5'), $name) . '</a>',
                    'dismissible' => false,
                );
            }
        }

        return $this;
    }

    public function registerAdminNotices()
    {
        if ($this->notices) {
            // Admin notice display output
            echo '<div class="notice notice-warning is-dismissible fc5-admin-notice">';
            echo '<div class="fc5-notice-logo"></div>';
            echo ' <p class="fc5-notice-title">';
            echo 'The following plugins conflict with Falcon5Translate, please uninstall them first.';
            echo ' </p>';
            echo '<ul class="fc5-notice-body fc5-red">';
            foreach ($this->notices as $slug => $notice) {
                $admin_display_msg = ($notice['msg'] ?? '');
                $admin_display_title = ($notice['title'] ?? '');
                $admin_display_link = ($notice['link'] ?? '');
//            $admin_display_dismissible= ($notice['dismissible'] ?? true);
                echo '<li>' . $admin_display_link . '</li>';

            }
            echo '</ul>';
            echo '</div>';
        }
    }
}